<!doctype html><html lang=zh-hans>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta http-equiv=x-ua-compatible content="IE=edge">
<meta name=author content="小李刀刀">
<meta name=description content="Spiral 框架包含 spiral/security 安全组件，提供了根据权限列表授权用户/行动者访问特定资源或行为的能力。安全组件实现了 NIST RBAC 研究 中阐述的“扁平 RBAC”设计模式。 该安全组件包括多项附加功能，比如： 用于控制权限/许可上下文的额外的 rules 层 通过通配符模式为一个角色分配多个权限 用高优先级规则覆盖已分配给角色的权限">
<meta name=theme-color content="#3f51b5">
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css integrity="sha256-4w9DunooKSr3MFXHXWyFER38WmPdm361bQS/2KUWZbU=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-light>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-dark disabled>
<script src=https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.1.2/lazysizes.min.js integrity="sha256-Md1qLToewPeKjfAHU1zyPwOutccPAm5tahnaw7Osw0A=" crossorigin=anonymous async></script>
<link rel=stylesheet href="https://fonts.font.im/css?family=Source+Code+Pro:300,400,500,600,700&subset=latin-ext&display=swap">
<link rel=stylesheet href=/css/academic.css>
<script>(function(b,d,e,a,g){b[a]=b[a]||[],b[a].push({'gtm.start':(new Date).getTime(),event:'gtm.js'});var f=d.getElementsByTagName(e)[0],c=d.createElement(e),h=a!='dataLayer'?'&l='+a:'';c.async=!0,c.src='https://www.googletagmanager.com/gtm.js?id='+g+h,f.parentNode.insertBefore(c,f)})(window,document,'script','dataLayer','GTM-5KZH8N7')</script>
<link rel=manifest href=/index.webmanifest>
<link rel=icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_32x32_fill_lanczos_center_3.png>
<link rel=apple-touch-icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_192x192_fill_lanczos_center_3.png>
<link rel=canonical href=https://studyspiral.cn/docs/security/rbac/>
<meta property="twitter:card" content="summary">
<meta property="og:site_name" content="Spiral中文网">
<meta property="og:url" content="https://studyspiral.cn/docs/security/rbac/">
<meta property="og:title" content="基于角色的权限控制 | Spiral中文网">
<meta property="og:description" content="Spiral 框架包含 spiral/security 安全组件，提供了根据权限列表授权用户/行动者访问特定资源或行为的能力。安全组件实现了 NIST RBAC 研究 中阐述的“扁平 RBAC”设计模式。 该安全组件包括多项附加功能，比如： 用于控制权限/许可上下文的额外的 rules 层 通过通配符模式为一个角色分配多个权限 用高优先级规则覆盖已分配给角色的权限"><meta property="og:image" content="https://studyspiral.cn/images/logo.svg">
<meta property="twitter:image" content="https://studyspiral.cn/images/logo.svg"><meta property="og:locale" content="zh-Hans">
<meta property="article:published_time" content="2020-04-12T23:24:50+08:00">
<meta property="article:modified_time" content="2020-08-28T15:38:18+08:00">
<script src=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.js integrity="sha256-5VhCqFam2Cn+yjw61zbBNrbHVJ6SRydPeKopYlngbiQ=" crossorigin=anonymous></script>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.css integrity="sha256-zQ0LblD/Af8vOppw18+2anxsuaz3pWYyVWi+bTvTH8Q=" crossorigin=anonymous>
<script>window.addEventListener("load",function(){window.cookieconsent.initialise({palette:{popup:{background:"#3f51b5",text:"#fff"},button:{background:"#fff",text:"#3f51b5"}},theme:"classic",content:{message:"本网站使用cookies来确保您在本网站上获得最佳体验。",dismiss:"知道了!",link:"了解更多",href:"https://www.cookiesandyou.com"}})})</script>
<title>基于角色的权限控制 | Spiral中文网</title>
</head>
<body id=top data-spy=scroll data-offset=70 data-target=#TableOfContents>
<aside class=search-results id=search>
<div class=container>
<section class=search-header>
<div class="row no-gutters justify-content-between mb-3">
<div class=col-6>
<h1>搜索</h1>
</div>
<div class="col-6 col-search-close">
<a class=js-search href=#><i class="fas fa-times-circle text-muted" aria-hidden=true></i></a>
</div>
</div>
<div id=search-box>
<input name=q id=search-query placeholder=搜索... autocapitalize=off autocomplete=off autocorrect=off spellcheck=false type=search>
</div>
</section>
<section class=section-search-results>
<div id=search-hits>
</div>
</section>
</div>
</aside>
<nav class="navbar navbar-expand-lg navbar-light compensate-for-scrollbar" id=navbar-main>
<div class=container>
<div class="d-none d-lg-inline-flex">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<button type=button class=navbar-toggler data-toggle=collapse data-target=#navbar-content aria-controls=navbar aria-expanded=false aria-label=切换导航>
<span><i class="fas fa-bars"></i></span>
</button>
<div class="navbar-brand-mobile-wrapper d-inline-flex d-lg-none">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<div class="navbar-collapse main-menu-item collapse justify-content-end" id=navbar-content>
<ul class="navbar-nav d-md-inline-flex">
<li class=nav-item>
<a class=nav-link href=/docs/basics/quick-start/><span>教程</span></a>
</li>
<li class=nav-item>
<a class="nav-link active" href=/docs/><span>文档</span></a>
</li>
<li class=nav-item>
<a class=nav-link href=/post/><span>文章</span></a>
</li>
</ul>
</div>
<ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2">
<li class=nav-item>
<a class="nav-link js-search" href=#><i class="fas fa-search" aria-hidden=true></i></a>
</li>
</ul>
</div>
</nav>
<div class="container-fluid docs">
<div class="row flex-xl-nowrap">
<div class="col-12 col-md-3 col-xl-2 docs-sidebar">
<form class="docs-search d-flex align-items-center">
<button class="btn docs-toggle d-md-none p-0 mr-3" type=button data-toggle=collapse data-target=#docs-nav aria-controls=docs-nav aria-expanded=false aria-label="Toggle section navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<input name=q type=search class=form-control placeholder=搜索... autocomplete=off>
</form>
<nav class="collapse docs-links" id=docs-nav>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/extension/dotenv/>Dotenv</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/>总览</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li>
<a href=/docs/>Spiral介绍</a>
</li>
<li>
<a href=/docs/about/contributing/>贡献指引</a>
</li>
<li>
<a href=/docs/about/semver/>版本说明</a>
</li>
<li>
<a href=/docs/about/license/>授权协议</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/psr-15/>定制 PSR-15 处理器</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/start/install/>快速开始</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/start/install/>安装指引</a>
</li>
<li>
<a href=/docs/start/workers/>应用工作进程</a>
</li>
<li>
<a href=/docs/start/structure/>应用程序结构</a>
</li>
<li>
<a href=/docs/start/configuration/>默认配置</a>
</li>
<li>
<a href=/docs/start/commands/>控制台命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/basics/quick-start/>入门基础</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/basics/quick-start/>上手指南</a>
</li>
<li>
<a href=/docs/basics/scaffolding/>脚手架</a>
</li>
<li>
<a href=/docs/basics/prototype/>原型开发辅助</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/framework/design/>核心框架</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/framework/design/>设计理念</a>
</li>
<li>
<a href=/docs/framework/application-server/>应用服务器</a>
</li>
<li>
<a href=/docs/framework/config/>配置对象</a>
</li>
<li>
<a href=/docs/framework/kernel/>内核与环境</a>
</li>
<li>
<a href=/docs/framework/container/>容器</a>
</li>
<li>
<a href=/docs/framework/bootloaders/>引导程序</a>
</li>
<li>
<a href=/docs/framework/scopes/>IoC 作用域</a>
</li>
<li>
<a href=/docs/framework/memory/>静态高速缓存</a>
</li>
<li>
<a href=/docs/framework/finalizers/>终结器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cookbook/annotated-routes/>速查手册</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cookbook/annotated-routes/>注解式路由</a>
</li>
<li>
<a href=/docs/cookbook/injector/>容器注入器</a>
</li>
<li>
<a href=/docs/cookbook/domain-core/>领域内核、控制器</a>
</li>
<li>
<a href=/docs/cookbook/golang-library/>Golang服务集成</a>
</li>
<li>
<a href=/docs/cookbook/custom-dispatcher/>自定义调度器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/component/files/>常用组件</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/component/files/>文件和目录</a>
</li>
<li>
<a href=/docs/component/reactor/>代码生成</a>
</li>
<li>
<a href=/docs/component/tokenizer/>静态分析工具</a>
</li>
<li>
<a href=/docs/component/metrics/>应用指标</a>
</li>
<li>
<a href=/docs/component/data-grid/>数据网格</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/console/configuration/>控制台</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/console/configuration/>安装和配置</a>
</li>
<li>
<a href=/docs/console/commands/>用户命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/configuration/>HTTP</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/http/configuration/>安装配置</a>
</li>
<li>
<a href=/docs/http/lifecycle/>请求生命周期</a>
</li>
<li>
<a href=/docs/http/request-response/>请求和响应</a>
</li>
<li>
<a href=/docs/http/routing/>路由</a>
</li>
<li>
<a href=/docs/http/errors/>错误页面</a>
</li>
<li>
<a href=/docs/http/middleware/>中间件</a>
</li>
<li>
<a href=/docs/http/golang/>Golang 中间件</a>
</li>
<li>
<a href=/docs/http/cookies/>Cookies</a>
</li>
<li>
<a href=/docs/http/session/>Session</a>
</li>
<li>
<a href=/docs/http/csrf/>CSRF 防护</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/security/encrypter/>安全</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li>
<a href=/docs/security/encrypter/>数据加密</a>
</li>
<li>
<a href=/docs/security/validation/>数据验证</a>
</li>
<li class=active>
<a href=/docs/security/rbac/>基于角色的权限控制</a>
</li>
<li>
<a href=/docs/security/authentication/>用户认证</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/filters/configuration/>请求过滤</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/filters/configuration/>安装和配置</a>
</li>
<li>
<a href=/docs/filters/filter/>过滤器</a>
</li>
<li>
<a href=/docs/filters/composite/>复合过滤器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/database/configuration/>数据库</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/database/configuration/>安装与配置</a>
</li>
<li>
<a href=/docs/database/access/>访问数据</a>
</li>
<li>
<a href=/docs/database/isolation/>逻辑隔离</a>
</li>
<li>
<a href=/docs/database/query-builders/>查询构造器</a>
</li>
<li>
<a href=/docs/database/transactions/>Transactions</a>
</li>
<li>
<a href=/docs/database/introspection/>Schema Introspection</a>
</li>
<li>
<a href=/docs/database/declaration/>Declaration</a>
</li>
<li>
<a href=/docs/database/migrations/>Migrations</a>
</li>
<li>
<a href=/docs/database/errata/>Errata</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cycle/configuration/>Cycle ORM</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cycle/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/queue/configuration/>队列任务</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/queue/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/queue/scraper/>网站爬虫</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/views/configuration/>视图</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/views/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/stempler/configuration/>Stempler 模板</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/stempler/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/stempler/directives/>Directives</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>国际化</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>GRPC</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>事件广播</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>调试及性能</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>扩展</a>
</div>
</nav>
</div>
<div class="d-none d-xl-block col-xl-2 docs-toc">
<ul class="nav toc-top">
<li><a href=# id=back_to_top class=docs-toc-title>在本页</a></li>
</ul>
<nav id=TableOfContents>
<ul>
<li><a href=#行为人actor>行为人（Actor）</a></li>
<li><a href=#守卫接口guardinterface>守卫接口（GuardInterface）</a>
<ul>
<li><a href=#权限上下文>权限上下文</a></li>
</ul>
</li>
<li><a href=#权限管理>权限管理</a>
<ul>
<li><a href=#创建角色>创建角色</a></li>
<li><a href=#权限>权限</a></li>
<li><a href=#通配符关联>通配符关联</a></li>
<li><a href=#排除权限>排除权限</a></li>
</ul>
</li>
<li><a href=#规则>规则</a>
<ul>
<li><a href=#自定义规则>自定义规则</a></li>
<li><a href=#静态规则>静态规则</a></li>
</ul>
</li>
<li><a href=#guarded-注解>@Guarded 注解</a></li>
</ul>
</nav>
</div>
<main class="col-12 col-md-9 col-xl-8 py-md-3 pl-md-5 docs-content" role=main>
<article class=article>
<div class="alert alert-warning" role=alert>
官方文档中文版翻译工作仍在进行中，欢迎 <a href=/post/join-translation/>参与翻译</a>。
</div>
<div class=docs-article-container>
<h1>基于角色的权限控制</h1>
<div class=article-style>
<p>Spiral 框架包含 <code>spiral/security</code> 安全组件，提供了根据权限列表授权用户/行动者访问特定资源或行为的能力。安全组件实现了
<a href=https://csrc.nist.gov/projects/role-based-access-control target=_blank rel=noopener>NIST RBAC 研究</a> 中阐述的“扁平 RBAC”设计模式。</p>
<p>该安全组件包括多项附加功能，比如：</p>
<ul>
<li>用于控制权限/许可上下文的额外的 <em>rules</em> 层</li>
<li>通过通配符模式为一个角色分配多个权限</li>
<li>用高优先级规则覆盖已分配给角色的权限</li>
</ul>
<blockquote>
<p>借助这些附加功能，可以使用该安全组件作为 ACL, DAC 和 ABAC 安全模型的框架。</p>
</blockquote>
<p>在项目中使用该安全组件，需要通过激活 <code>Spiral\Bootloader\Security\GuardBootloader</code> 引导程序来启用组件，但不需要对组件进行配置。</p>
<blockquote>
<p>在 Web 和 GRPC 应用程序模板中已经默认包含和启用了该安全组件。</p>
</blockquote>
<h2 id=行为人actor>行为人（Actor）</h2>
<p>应用中的所有权限会根据与当前 <code>Spiral\Security\ActorInterface</code> 关联的角色来进行授予。</p>
<pre><code class=language-php>interface ActorInterface
{
    public function getRoles(): array;
}
</code></pre>
<blockquote>
<p>请在用户请求时使用 IoC 作用域来设置行为人.</p>
</blockquote>
<p>要了解如何将已认证用户作为行为人，请阅读
<a href=/docs/security/authentication/>用户认证文档</a>.</p>
<p>默认情况下，应用程序使用 <code>Spiral\Security\Actor\Guest</code> 作为默认的行为人，你可以在全局范围或者 IoC 作用域内用容器绑定进行行为人设置。</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Core\ScopeInterface;
use Spiral\Security\Actor\Actor;
use Spiral\Security\ActorInterface;

class HomeController
{
    public function index(ScopeInterface $scope)
    {
        return $scope-&gt;runScope([ActorInterface::class =&gt; new Actor(['admin'])], function () {

            // 当前请求作用域内行为人拥有 `admin` 角色
            return 'ok';
        });
    }
}
</code></pre>
<blockquote>
<p>你可以使用领域核心拦截器、GRPC 拦截器、HTTP 中间件、自定义 IoC 作用域等手段来设置 Actor。</p>
</blockquote>
<p>为了简化文档，下面的代码通过自定义的引导程序设置全局范围内可见的默认行为人：</p>
<pre><code class=language-php>namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Core\Container;
use Spiral\Security\Actor\Actor;
use Spiral\Security\ActorInterface;

class SecurityBootloader extends Bootloader
{
    public function boot(Container $container)
    {
        $container-&gt;bindSingleton(ActorInterface::class, new Actor(['user']));
    }
}
</code></pre>
<h2 id=守卫接口guardinterface>守卫接口（GuardInterface）</h2>
<p>要使用 RBAC 组件，必须注册可用的角色，并在角色和权限之间创建关联，可以在设置行为人的同一个引导程序中，使用 <code>Spiral\Security\PermissionsInterface</code> 接口来完成这项工作：</p>
<pre><code class=language-php>namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Core\Container;
use Spiral\Security\Actor\Actor;
use Spiral\Security\ActorInterface;
use Spiral\Security\PermissionsInterface;

class ActorBootloader extends Bootloader
{
    public function boot(Container $container, PermissionsInterface $rbac)
    {
        $container-&gt;bindSingleton(ActorInterface::class, new Actor(['user']));

        $rbac-&gt;addRole('user');
        $rbac-&gt;associate('user', 'home.read');
    }
}
</code></pre>
<blockquote>
<p>下面的文档会详细解释“角色-规则-权限（role-rule-permission）的关联。</p>
</blockquote>
<p>一旦引导程序被激活，就可以使用 <code>Spiral\Core\GuardInterface</code> 来检查用户是否具有特定权限，守卫（Guard）会自动通过当前活动的作用域，使用 <code>Spiral\Security\GuardScope</code> 解析当前活动的行为人。该接口提供了名为 <code>allows</code> 的方法，用于检查行为人是否具有指定的权限：</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Security\GuardInterface;

class HomeController
{
    public function index(GuardInterface $guard)
    {
        if (!$guard-&gt;allows('home.read')) {
            return '不可读';
        }

        return '可读';
    }
}
</code></pre>
<blockquote>
<p>你可以改变默认行为人的角色来看看它对结果有什么影响。</p>
</blockquote>
<p>当然为了开发更便利，可以使用原型开发辅助提供的 <code>guard</code> 属性。</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Prototype\Traits\PrototypeTrait;

class HomeController
{
    use PrototypeTrait;

    public function index()
    {
        if (!$this-&gt;guard-&gt;allows('home.read')) {
            return '不可读';
        }

        return '可读';
    }
}
</code></pre>
<blockquote>
<p><code>GuardInterface</code> 可以用于控制器、服务和视图。</p>
</blockquote>
<h3 id=权限上下文>权限上下文</h3>
<p>守卫对象的 <code>allows</code> 方法支持第二个参数，该参数代表权限上下文，通常它必须包含当前行为人试图访问或改动的目标实体对象。</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Security\GuardInterface;

class HomeController
{
    public function index(GuardInterface $guard)
    {
        if (!$guard-&gt;allows('home.read', ['key' =&gt; 'value'])) {
            return '不可读';
        }

        return '可读';
    }
}
</code></pre>
<p>接下来，我们一起了解一下如何使用上下文来创建更为复杂的角色-权限关联。</p>
<h2 id=权限管理>权限管理</h2>
<p>RBAC 组件的核心部分是 <code>Spiral\Security\PermissionInterface</code> 接口。尽管你可以在你的实现中用它进行动态角色和权限的配置，但默认情况下，它的设计目的是用于在引导程序中配置角色和权限映射。</p>
<h3 id=创建角色>创建角色</h3>
<p>每个应用程序都必须使用 <code>addRole</code> 方法在 RBAC 组件中注册可用的用户角色：</p>
<pre><code class=language-php>namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Security\PermissionsInterface;

class SecurityBootloader extends Bootloader
{
    public function boot(PermissionsInterface $rbac)
    {
        $rbac-&gt;addRole('guest');
    }
}
</code></pre>
<h3 id=权限>权限</h3>
<p>一旦角色创建好，就可以用 <code>associate</code> 方法将它们和具体权限进行关联：</p>
<pre><code class=language-php>namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Security\PermissionsInterface;

class SecurityBootloader extends Bootloader
{
    public function boot(PermissionsInterface $rbac)
    {
        $rbac-&gt;addRole('guest');

        $rbac-&gt;associate('guest', 'home.read');
    }
}
</code></pre>
<h3 id=通配符关联>通配符关联</h3>
<p>你也可以一次性把单个权限与多个权限进行关联：</p>
<pre><code class=language-php>$rbac-&gt;associate('guest', 'home.(read|write)');
</code></pre>
<p>你还可以使用通配符 <code>*</code> 来创建角色与某个命名空间下的所有权限的关联：</p>
<pre><code class=language-php>$rbac-&gt;associate('guest', 'home.*');
</code></pre>
<p>注意，如果你使用了带 <code>.</code> 分隔符的多级命名空间，只有第一级的命名空间会被关联：</p>
<pre><code class=language-php>$rbac-&gt;associate('guest', 'home.*');
$rbac-&gt;associate('guest', 'home.*.*');
// ...
</code></pre>
<h3 id=排除权限>排除权限</h3>
<p>有时候，你需要授予某个命名空间下的所有权限，排除特定的少数权限。这种情况可以用第三个参数，第三个参数可以指定覆盖规则。比如要禁止某项已经授予的权限，就可以用 <code>Spiral\Security\Rule\ForbidRule</code>:</p>
<pre><code class=language-php>namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Security\PermissionsInterface;
use Spiral\Security\Rule\ForbidRule;

class SecurityBootloader extends Bootloader
{
    public function boot(PermissionsInterface $rbac)
    {
        $rbac-&gt;addRole('guest');

        $rbac-&gt;associate('guest', 'home.*');
        $rbac-&gt;associate('guest', 'home.read', ForbidRule::class);
    }
}
</code></pre>
<p>第三个参数的默认值是 <code>AllowRule</code>。上面的例子与以下表达形式相同：</p>
<pre><code class=language-php>namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Security\PermissionsInterface;
use Spiral\Security\Rule;

class SecurityBootloader extends Bootloader
{
    public function boot(PermissionsInterface $rbac)
    {
        $rbac-&gt;addRole('guest');

        $rbac-&gt;associate('guest', 'home.*', Rule\AllowRule::class);
        $rbac-&gt;associate('guest', 'home.read', Rule\ForbidRule::class);
    }
}
</code></pre>
<blockquote>
<p>守卫（Guard）会检查行为人的所有角色，其中至少要有一个角色被授予了相关权限，行为人才会拥有该项权限。</p>
</blockquote>
<h2 id=规则>规则</h2>
<p>如上所述，所有的角色到权限的关联都由一套规则来控制。每个规则都必须实现 <code>Spiral\Security\RuleInterface</code> 接口。</p>
<pre><code class=language-php>interface RuleInterface
{
    public function allows(ActorInterface $actor, string $permission, array $context): bool;
}
</code></pre>
<p>在检查某个角色的某项权限时，对应的规则接收到由 <code>GuardInterface</code>-><code>allows</code> 方法提供的当前上下文：</p>
<pre><code class=language-php>if (!$guard-&gt;allows('home.read', ['key' =&gt; 'value'])) {
    return '不可读';
}
</code></pre>
<p>这样的实现允许你在角色和权限集之间建立复杂的规则关联。</p>
<blockquote>
<p>默认规则 <code>AllowRule</code> 和 <code>ForbidRule</code> 总是相应地返回 <code>true</code> 和 <code>false</code>.</p>
</blockquote>
<h3 id=自定义规则>自定义规则</h3>
<p>如果需要创建自定义规则，只需要实现 <code>Spiral\Security\RuleInterface</code> 接口。例如，我们创建只在上下文中 <code>key</code> 的值为 <code>value</code> 时才授予权限的一个规则：</p>
<pre><code class=language-php>namespace App\Security;

use Spiral\Security\ActorInterface;
use Spiral\Security\RuleInterface;

class SampleRule implements RuleInterface
{
    public function allows(ActorInterface $actor, string $permission, array $context): bool
    {
        return $context['key'] === 'value';
    }
}
</code></pre>
<p>定义好之后，你可以通过规则的类名将其应用于角色权限关联：</p>
<pre><code class=language-php>namespace App\Bootloader;

use App\Security\SampleRule;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Security\PermissionsInterface;

class SecurityBootloader extends Bootloader
{
    public function boot(PermissionsInterface $rbac)
    {
        $rbac-&gt;addRole('guest');

        $rbac-&gt;associate('guest', 'home.*', SampleRule::class);
    }
}
</code></pre>
<p>现在，改变 <code>allows</code> 方法中的上下文可以让权限检查通过或拒绝：</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Prototype\Traits\PrototypeTrait;

class HomeController
{
    use PrototypeTrait;

    public function index()
    {
        if ($this-&gt;guard-&gt;allows('home.read', ['key' =&gt; 'value'])) {
            echo '通过';
        }

        if ($this-&gt;guard-&gt;allows('home.read', ['key' =&gt; 'else'])) {
            echo '拒绝';
        }
    }
}
</code></pre>
<blockquote>
<p>可以使用行为人接口创建更负责的规则。</p>
</blockquote>
<p>传入业务实体作为上下文来检查权限：</p>
<pre><code class=language-php>if ($this-&gt;guard-&gt;allows('post.edit', ['post' =&gt; $post])) {
    echo '通过';
}
</code></pre>
<p>还可以定义规则来检查当前用户（行为人）是否实体的作者：</p>
<pre><code class=language-php>class SampleRule implements RuleInterface
{
    public function allows(ActorInterface $actor, string $permission, array $context): bool
    {
        return $context['post']-&gt;user === $actor;
    }
}
</code></pre>
<h3 id=静态规则>静态规则</h3>
<p>为了简化规则的创建，可以使用 <code>Spiral\Security\Rule</code>, 它通过 <code>check</code> 方法来启用了方法注入：</p>
<pre><code class=language-php>namespace App\Security;

use Spiral\Security\Rule;

class SampleRule extends Rule
{
    public function check(string $key): bool
    {
        return $key === 'value';
    }
}
</code></pre>
<blockquote>
<p>通过这里的方法注入，你可以使用应用程序的任何服务。</p>
</blockquote>
<p>建议将规则声明为单例模式，以提升应用程序的性能：</p>
<pre><code class=language-php>namespace App\Security;

use Spiral\Core\Container\SingletonInterface;
use Spiral\Security\Rule;

class SampleRule extends Rule implements SingletonInterface
{
    public function check(string $key): bool
    {
        return $key === 'value';
    }
}
</code></pre>
<h2 id=guarded-注解>@Guarded 注解</h2>
<p>在控制器方法上，可以使用 <code>Guarded</code> 注解来自动检查对
<a href=/docs/cookbook/domain-core/>领域核心</a>的访问权限。</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Domain\Annotation\Guarded;

class HomeController
{
    /**
     * @Guarded(&quot;home.index&quot;, else=&quot;notFound&quot;)
     */
    public function index()
    {
        return 'OK';
    }
}
</code></pre>
</div>
<div class=article-widget>
<div class=post-nav>
<div class=post-nav-item>
<div class=meta-nav>上一页</div>
<a href=/docs/queue/configuration/ rel=next>Configuration</a>
</div>
<div class=post-nav-item>
<div class=meta-nav>下一页</div>
<a href=/docs/security/authentication/ rel=prev>用户认证</a>
</div>
</div>
</div>
</div>
<div class=body-footer>
<p>最近更新于 2020-08-28</p>
<p class=edit-page>
<a href=https://github.com/krwu/spiraldocs/edit/feat/chinese/zh_CN/security/rbac.md>
<i class="fas fa-pen pr-2"></i>编辑本页
</a>
</p>
</div>
</article>
<footer class=site-footer>
<p class=powered-by><span class=copyright>© 2019 - 2021 <a href=https://studyspiral.cn/>StudySpiral</a> All rights reserved.</span>
</p>
<p class=powered-by>
<a href=http://www.beian.miit.gov.cn/ target=_blank rel="noopener noreferer">粤ICP备14011364号</a>
<a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44030402001866" target=_blank rel="noopener noreferer"><img style=display:inline-block src=/img/gaba.png>粤公网安备 44030402001866号</a>
</p>
<p id=webify class=powered-by style=display:flex><span style="margin:0 .2rem 0 0;display:block;height:20px;line-height:20px">Powered by</span> <a href=https://webify.cloudbase.net/ target=_blank rel=noopener>CloudBase Webify</a></p>
<script async defer>window.addEventListener('DOMContentLoaded',()=>{const{host:a}=window.location;(a.toLocaleLowerCase()==='docs.studyspiral.cn'||a.indexOf(".app.tcloudbase.com"))&&(document.getElementById('webify').style.display='flex')})</script>
</footer>
</main>
</div>
</div>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js integrity="sha256-lqvxZrPLtfffUl2G/e7szqSvPBILGbwmsGE1MKlOi0Q=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js integrity="sha256-CBrpuqrMhXwcLLUd5tvQ4euBHCdh7wGlDfNz8vbu/iI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js integrity="sha256-eOgo0OtLL4cdq7RdwRUiGKLX9XsIJ7nGhWEKbohmVAQ=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/languages/go.min.js></script>
<script>const code_highlighting=!0</script>
<script>const isSiteThemeDark=!1</script>
<script>const search_config={indexURI:"/index.json",minLength:1,threshold:.3},i18n={no_results:"没有找到结果",placeholder:"搜索...",results:"搜索结果"},content_type={post:"文章",project:"项目",publication:"出版物",talk:"演讲"}</script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.1/anchor.min.js integrity="sha256-pB/deHc9CGfFpJRjC43imB29Rse8tak+5eXqntO94ck=" crossorigin=anonymous></script>
<script>anchors.add()</script>
<script id=search-hit-fuse-template type=text/x-template>
      <div class="search-hit" id="summary-{{key}}">
      <div class="search-hit-content">
        <div class="search-hit-name">
          <a href="{{relpermalink}}">{{title}}</a>
          <div class="article-metadata search-hit-type">{{type}}</div>
          <p class="search-hit-description">{{snippet}}</p>
        </div>
      </div>
      </div>
    </script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin=anonymous></script>
<script src=/js/academic.min.6f1005d1a84220e2f466ff3d8e712f31.js></script>
<div id=modal class="modal fade" role=dialog>
<div class=modal-dialog>
<div class=modal-content>
<div class=modal-header>
<h5 class=modal-title>引用</h5>
<button type=button class=close data-dismiss=modal aria-label=Close>
<span aria-hidden=true>&#215;</span>
</button>
</div>
<div class=modal-body>
<pre><code class="tex hljs"></code></pre>
</div>
<div class=modal-footer>
<a class="btn btn-outline-primary my-1 js-copy-cite" href=# target=_blank>
<i class="fas fa-copy"></i> 复制
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href=# target=_blank>
<i class="fas fa-download"></i> 下载
</a>
<div id=modal-error></div>
</div>
</div>
</div>
</div>
</body>
</html>